'use strict';
let gulp = require('gulp');
let typescript = require('gulp-typescript');
let nodemon = require('gulp-nodemon');
let rimraf = require('rimraf');
const alias = require('gulp-ts-alias');

const CLEAN_BUILD = 'clean:build';
const COMPILE_TYPESCRIPT = 'compile:typescript';
const BUILD = 'build';

const TS_SRC_GLOB = './src/**/*.ts';
const TS_GLOB = [TS_SRC_GLOB];

const tsProject = typescript.createProject('tsconfig.json');

// Removes the ./build directory with all its content.
gulp.task(CLEAN_BUILD, function (callback) {
  rimraf('./build', callback);
});


gulp.task(COMPILE_TYPESCRIPT, function () {
  return gulp.src(TS_GLOB)
    .pipe(alias(tsProject.config)) // 别名设置，打包后@全部转换为相对路径
    // .pipe(sourcemaps.init())
    .pipe(tsProject())
    // .pipe(sourcemaps.write('.', { sourceRoot: '../src' }))
    .pipe(gulp.dest('build'));
});

// Runs all required steps for the build in sequence.
gulp.task(BUILD, gulp.series(COMPILE_TYPESCRIPT));

// 本地启动使用的task，去掉不必要的任务，提高速度
gulp.task('dev', function () {
  return gulp.src(TS_GLOB)
    .pipe(alias(tsProject.config)) // 别名设置，打包后@全部转换为相对路径
    .pipe(tsProject())
    .pipe(gulp.dest('build'));
});


// Runs the build task and starts the server every time changes are detected.
gulp.task('watch', gulp.series('dev', function () {
  return nodemon({
    ext: 'ts json',
    script: 'build/app.js',
    watch: ['src/*'],
    legacyWatch: true,
    tasks: ['dev']
  });
}));
